cmake_minimum_required(VERSION 3.14)

project(instrdrawer LANGUAGES C ASM)

message(${CMAKE_PROJECT_VERSION})

set(CMAKE_INCLUDE_CURRENT_DIR ON)

include_directories(
    DevicePro
    Inc
    Src
    MDK-ARM
    ../Drivers/GD32F4xx_standard_peripheral/Include
    ../Drivers/CMSIS
    ../Drivers/CMSIS/GD/GD32F4xx/Include
#    ../Drivers/CMSIS/GD
#    ../Drivers/GD32F4xx_standard_peripheral/Source
#    ../Drivers/CMSIS/GD/GD32F4xx/Source/ARM
#    ../Drivers/CMSIS/GD/GD32F4xx/Source
)


file(GLOB_RECURSE C_FILES
        DevicePro/crc.c
        DevicePro/crc.h
        DevicePro/flash_if.c
        DevicePro/flash_if.h
        DevicePro/targetbl_main.c
        DevicePro/targetbl_commands.c
        DevicePro/targetbl_infoblock.c
        DevicePro/targetbl_config.h
        DevicePro/targetbl_interface.h
        DevicePro/user_global.h
        Src/*.c
        Src/*.h
        Inc/*.c
        Inc/*.h
)

file(GLOB_RECURSE KERNEL_FILES
    Src/startup_gd32f405.s
    Src/system_gd32f4xx.c
    Src/system_gd32f4xx.h
    )

#file(GLOB_RECURSE DRIVER_FILES
#    ../Drivers/GD32F4xx_standard_peripheral/Source/*.c
#    ../Drivers/GD32F4xx_standard_peripheral/Include/*.h
#    ../Drivers/CMSIS/*.c
#    ../Drivers/CMSIS/GD/GD32F4xx/Source/system_gd32f4xx.c
#    )

set(CMAKE_C_FLAGS  "${CMAKE_C_FLAGS}
    -c --cpu Cortex-M4.fp -g -O0 --apcs=interwork --split_sections"
    )
set(CMAKE_ASM_FLAGS "--cpu Cortex-M4.fp -g --apcs=interwork"
    )

set(LINK_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/MDK-ARM/bootloader/bootloader.sct)
set(LINK_OPTIONS
    --strict
    --summary_stderr
    --info=summarysizes
    --map
    --xref
    --callgraph
    --symbols
    --cpu=Cortex-M4.fp
    --scatter=${LINK_SCRIPT}
    --info=sizes
    --info=totals
    --info=unused
    --info=veneers
#    --list=${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/g32x_instrdrawer_a1_release.map
#    -o ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/g32x_instrdrawer_a1_release.axf
    )

set(SOURCE_FILES  ${C_FILES} ${KERNEL_FILES})

#add_library(driver  ${DRIVER_FILES})
add_executable(bootloader  ${SOURCE_FILES})

target_link_options(bootloader
    PRIVATE ${LINK_OPTIONS})

target_link_libraries(bootloader
    PUBLIC drivers)

set(ELF_FILE g32x_${PROJECT_NAME}_bl_a${CMAKE_PROJECT_VERSION_MAJOR}.elf)
set(HEX_FILE g32x_${PROJECT_NAME}_bl_a${CMAKE_PROJECT_VERSION_MAJOR}.hex)
set(BIN_FILE g32x_${PROJECT_NAME}_bl_a${CMAKE_PROJECT_VERSION_MAJOR}.bin)
set(elfPath  fromelf)

# refer: https://developer.arm.com/documentation/100071/0612/fromelf-command-line-options?lang=en
add_custom_command(TARGET bootloader  POST_BUILD
    COMMAND ${elfPath} --i32combined $<TARGET_FILE:bootloader> --output=${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${HEX_FILE}
    COMMAND ${elfPath} --bincombined $<TARGET_FILE:bootloader> --output=${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${BIN_FILE}
    )

